/**
 * Static IO functions for reading input and printing output to the user
 *
 * @author Jonathan Walsh (jwalsh8484@gmail.com)
 */

package egs.client;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class ClientInput {

    private BufferedReader in;
    private static ClientInput instance;

    /**
     * Constructor for the client object this is a singleton object, so call 
     * the factory function below.
     */
    protected ClientInput() {
        in = new BufferedReader( new InputStreamReader( System.in ) );
    }

    /**
     * Factory function which creates the singleton if it doesn't exist, and 
     * returns it
     *
     * @return the static instance ClientInput
     */
    public static ClientInput getClientInputObject() {
        if ( instance == null ) instance = new ClientInput();
        return instance;
    }
    

    /**
     * Prompt the user for a string
     *
     * @param prompt - The string prompt
     * @return A string as inputted by the user
     * @except IOException Passed up from readLine() call
     */
    public String promptUserString( String prompt ) throws IOException {
        System.out.print( prompt + "? " );
        return in.readLine();
    }

    /**
     * Prompt the user for an integer
     *
     * @param prompt - The string prompt
     * @return An integer as inputted by the user
     * @except IOException Passed up from readLine() call
     */
    public int promptUserInt( String prompt ) throws IOException, 
                                                     NumberFormatException {
        System.out.print( prompt + " (int)? " );
        return Integer.parseInt( in.readLine() );
    }

    /**
     * Unit test program!
     */
    public static void main( String argv[] ) {

        System.out.println( "Test program for ClientIO" );

        ClientInput cio = null;
        try {
            cio = getClientInputObject();
        } catch ( Exception e ) {
            System.out.println( "Seriously the constructor failed?" );
            System.exit(1);
        }
        
        try {
            String returned = cio.promptUserString( "I need information!" );
            System.out.println( "I got: " + returned );
        } catch ( IOException ioe ) {
            System.out.println( "Something horrible happened: " + 
                                ioe.getMessage() );
            System.exit(1);
        }

        try {
            int retI = cio.promptUserInt( "I need information!" );
            System.out.println( "I got: " + retI );


        } catch ( NumberFormatException nfe ) {
            System.out.println( "Hey man that wasn't an INT, you did learn data types didn't you?" );
        } catch ( IOException ioe ) {
            System.out.println( "Something horrible happened: " + 
                                ioe.getMessage() );
            System.exit(1);
        }
    }

}